import pymysql


class DBUtil:
    # 定义类属性，为了解决报黄的问题
    conn = None

    # 链接数据库
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 关闭数据库
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 封装读取的方法
    @classmethod
    def query_db(cls, sql):

        result = None
        cursor = None
        try:
            # 创建数据库的链接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql,return 查询的结果
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("读取数据库报错:", err)
        finally:
            # 关闭游标
            cursor.close()
            # 关闭链接
            cls.__close_db()
            return result

    # 封装增删改的方法
    @classmethod
    def update_db(cls, sql):
        cursor = None
        try:
            # 创建数据库的链接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql，打印一下影响的行数
            cursor.execute(sql)
            affect_rows = cls.conn.affected_rows()
            print("影响数据库的行数：", affect_rows)
            # 事务的提交和回滚
            cls.conn.commit()
        except Exception as err:
            # 事务的回滚
            cls.conn.rollback()
            print("增删改数据库报错：", err)
            pass
        finally:
            # 关闭游标
            cursor.close()
            # 关闭链接
            cls.__close_db()


if __name__ == '__main__':
    # res = DBUtil.query_db("SELECT * FROM  t_book;")
    # print(res)
    res2 = DBUtil.update_db("UPDATE t_book Set `read` =`read`+1 where id =8;")

    pass

